package com.example.module.custom.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.module.custom.R;
import com.example.module.custom.R2;
import com.example.module.custom.adapter.BaseAdapter;
import com.example.module.custom.adapter.PQCListAdapter;
import com.example.module.custom.bean.PQCListBean;
import com.example.module.custom.http.HTTPURL;
import com.example.module.custom.utils.SoftKeyboardUtil;
import com.example.module.custom.utils.SpacesItemDecoration;
import com.example.module.custom.utils.ToastUtil;
import com.example.module.custom.view.CustomPartShadowPopupView;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.zxing.activity.CaptureActivity;
import com.nand.library.zxing.activity.CodeUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name BlockDemo
 * @class name：com.nand.module.function.ui
 * @classdescribe PQC list页面activity
 * @anthor ljp
 * @time 2020/1/6 15:44
 */
@Route(path = "/custom/PQCList")
public class PQCListActivity extends BaseActivity {
    @BindView(R2.id.tv_headline)
    TextView tvHeadline;
    @BindView(R2.id.real_add)
    RelativeLayout realAdd;
    @BindView(R2.id.iv_or_code)
    ImageView ivOrCode;
    @BindView(R2.id.et_equipment_number)
    EditText etEquipmentNumber;
    @BindView(R2.id.tv_query)
    TextView tvQuery;
    @BindView(R2.id.ll_query)
    LinearLayout llQuery;
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R2.id.real_back)
    RelativeLayout realBack;
    @BindView(R2.id.ll_empty)
    LinearLayout llEmpty;
    @BindView(R2.id.cb_value1)
    CheckBox cbValue1;
    private int page = 1;
    @Autowired(name = "type")
    public int flag;//1普通列表，2复查列表
    private ArrayList<PQCListBean.DataListBean> pqcListBeans;
    private PQCListAdapter pqcListAdapter;
    public static final int CODE_WORK_PROGRESS_BATCH = 1001;//在制品批次
    public static final int CODE_MATERIAL_ID = 1001;//材料夹具ID

    private CheckBox cbValue2;
    private RelativeLayout relativeLayout1;

    private String[] dataValue1;
    private String[] dataValue2;
    private CustomPartShadowPopupView popupViewResult;
    private CustomPartShadowPopupView popupViewType;
    private int typePosition = 0;
    private int resultPosition = 0;
    private String valueParam1;
    private String valueParam2;

    @Override
    protected int initLayout() {
        return R.layout.activity_pqclist;
    }

    private String search;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        pqcListBeans = new ArrayList<>();
        smartRefresh.autoRefresh();
        smartRefresh.setRefreshHeader(new ClassicsHeader(this));
        smartRefresh.setRefreshFooter(new ClassicsFooter(this));
        dataValue1 = getResources().getStringArray(R.array.text_type2);
        realAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ARouter.getInstance().build("/custom/PQCAdd")
                        .withInt("flag", 1)
                        .navigation(activity, 8888);
            }
        });
        pqcListAdapter = new PQCListAdapter(mContext, pqcListBeans, R.layout.item_pqc_list, flag);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(pqcListAdapter);
        recyclerView.addItemDecoration(new SpacesItemDecoration(15));
        pqcListAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(int postion, View view) {
                if (pqcListAdapter.getDataListBeanList() != null && pqcListAdapter.getDataListBeanList().size() != 0) {
                    PQCListBean.DataListBean dataListBean = pqcListAdapter.getDataListBeanList().get(postion);
                    ARouter.getInstance().build("/custom/PQCAdd")
                            .withString("oid", dataListBean.getOid())
                            .withInt("flag", flag == 1 ? 3 : 2)
                            .navigation(activity, flag == 2 ? 8888 : 0);
                }
            }
        });
        if (flag == 1) {
            tvHeadline.setText("PQC检验");
        } else {
            tvHeadline.setText("PQC不合格列表");
            realAdd.setVisibility(View.GONE);
        }
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //search = "";
                page = 1;
                initData();
                smartRefresh.finishRefresh(10000);
            }
        });
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initData();
                smartRefresh.finishLoadMore(10000);
            }
        });
        tvQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SoftKeyboardUtil.hideKeyboard(activity);
                search = etEquipmentNumber.getText().toString().trim();
                page = 1;
                initData();
            }
        });

        realBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        etEquipmentNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().length() == 0) {
                    if (smartRefresh.getVisibility() == View.GONE) {
                        //etEquipmentNumber.setText("");
                        search = "";
                        smartRefresh.setVisibility(View.VISIBLE);
                        llEmpty.setVisibility(View.GONE);
                    }
                }
            }
        });

        cbValue1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupViewResultList(view, dataValue1, "检查类型");
            }
        });

    }

    /**
     * @author ljp
     * @time 14:11
     * @describe 弹出筛选条件list(iqc来料单 ( 优先级)，iqc检验优先级)
     */
    private void showPopupViewResultList(View view, String[] data, final String value) {
        if (popupViewResult == null) {
            popupViewResult = (CustomPartShadowPopupView) new XPopup.Builder(activity)
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }

                        @Override
                        public void onDismiss() {
                            cbValue1.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(activity));
            popupViewResult.setStringData(data, null);
            popupViewResult.setCheckedPosition(resultPosition);
            popupViewResult.setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    resultPosition = position;
                    cbValue1.setText(position == 0 ? value : text);
                    page = 1;
                    initData();
                }
            });
        }
        popupViewResult.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // page = 1;
        // smartRefresh.autoRefresh();
    }

    @Override
    protected void initData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("current", page);//当前页数
        httpParams.put("size", 10);//每页显示个数
        httpParams.put("state", flag);//类型 1.pqc列表 2pcq不合格列表
        if (resultPosition > 0)
            httpParams.put("checkType", resultPosition - 1);
        if (!TextUtils.isEmpty(search))
            httpParams.put("search", search);

        // Log.e(TAG, "initData: -------------"+httpParams.toString());
        OkGoUtils.getInstance().post(this, HTTPURL.PQC_LIST, httpParams,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            String data = response.getDataInfo().toString();
                            PQCListBean pqcListBean = new Gson().fromJson(data, PQCListBean.class);
                            // Log.e(TAG, "onSuccess: ---pqcListBean--"+pqcListBean.getDataList().size());
                            if (page == 1 && (pqcListBean.getDataList() == null || pqcListBean.getDataList().size() == 0)) {
                                smartRefresh.setVisibility(View.GONE);
                                llEmpty.setVisibility(View.VISIBLE);
                                return;
                            }
                            smartRefresh.setVisibility(View.VISIBLE);
                            llEmpty.setVisibility(View.GONE);
                            if (page != 1 && (pqcListBean.getDataList() == null || pqcListBean.getDataList().size() == 0)) {
                                smartRefresh.finishLoadMoreWithNoMoreData();
                            } else {
                                if (page == 1) {
                                    pqcListBeans.clear();
                                    smartRefresh.finishRefresh();
                                }
                                pqcListBeans.addAll(pqcListBean.getDataList());
                                pqcListAdapter.notifyDataSetChanged();
                                //if (pqcListBean.getDataList() != null && pqcListBean.getDataList().size() != 0) {

                                // }
                            }
                            smartRefresh.finishLoadMore();
                            Log.i(TAG, "onSuccess: ---size---" + pqcListBean.getDataList().size());
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });
    }


    /**
     * @author ljp
     * @time 18:12
     * @describe 扫码
     */
    @OnClick(R2.id.iv_or_code)
    public void onViewClicked() {
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, CODE_WORK_PROGRESS_BATCH);
    }

    /**
     * @author ljp
     * @time 17:27
     * @describe 扫描二维码返回值
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == CODE_WORK_PROGRESS_BATCH) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String workResultCode = bundle.getString(CodeUtils.RESULT_STRING);
                    //ToastUtil.showShortToast(workResultCode);
                    Log.i(TAG, "onActivityResult: ----扫描结果-----" + workResultCode);
                    etEquipmentNumber.setText(workResultCode);
                    search = workResultCode;
                    page = 1;
                    initData();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.showShortToast("解析二维码失败", mContext);
                }
            }
        } else if (requestCode == CODE_MATERIAL_ID) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String resultCode1 = bundle.getString(CodeUtils.RESULT_STRING);
                    // ToastUtil.showShortToast(result);
                    etEquipmentNumber.setText(resultCode1);
                    Log.i(TAG, "onActivityResult: ----扫描结果-----" + resultCode1);
                    search = resultCode1;
                    page = 1;
                    initData();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.showShortToast("解析二维码失败", mContext);
                }
            }
        } else if (requestCode == 8888) {
            page = 1;
            smartRefresh.autoRefresh();
        }
    }
    /**
     * @author ljp
     * @time 17:44
     * @describe 根据编码查询数据
     *//*
    private void codeHttpData(String value) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("winNode", value);
        OkGoUtils.getInstance().post(mContext,HTTPURL.PQC_ADD_CODE_SELECT, httpParams, 1, true, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (response.getCode() == 200) {
                    String data = response.getDataInfo().toString();
                    Log.i(TAG, "onSuccess: -----" + response.getDataInfo().toString());
                    PQCDetailsBean pqcDetailsBean = new Gson().fromJson(data, PQCDetailsBean.class);
                    ARouter.getInstance().build("/custom/PQCAdd")
                            .withString("oid", pqcDetailsBean.getOid())
                            .withInt("flag", flag == 1 ? 3 : 2)
                            .navigation();
                }
            }
            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }*/
}
